import React, { Component, } from 'react';
import {
    NetInfo,
    Platform
} from 'react-native';

import Constant from '../Constant/Constant'
import Crypto from 'crypto-js/crypto-js'
import StorageUtils from '../Utils/StorageUtils'
import ToastUtils from '../Utils/ToastUtils'
import LoadingUtils from '../Utils/LoadingUtils'

export default class HttpUtils extends React.Component
{
    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static getJsonWithoutLoading(url, session, successCall, failCall)
    {
        console.log('url is ' + url);
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请打开手机网络开关');
                }
            }
        });
        var fetchOptions = {
            method: 'GET',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                "Tenant-Id": "000000",
                "Blade-Auth": "bearer " + session
            },
        };
        fetch(url, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                // Spinner.hide();
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.code == 200)
                {
                    successCall(responseJson.code, responseJson.data);
                }
                else
                {
                    failCall(responseJson.code, responseJson.msg);
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static getJson(url, session, successCall, failCall)
    {
        console.log('url is ' + url);
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请打开手机网络开关');
                }
            }
        });
        var fetchOptions = {
            method: 'GET',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                "Tenant-Id": "000000",
                "Blade-Auth": "bearer " + session
            },
        };
        LoadingUtils.showLoading();
        fetch(url, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                // Spinner.hide();
                LoadingUtils.dismissLoading();
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.code == 200)
                {
                    successCall(responseJson.code, responseJson.data);
                }
                else
                {
                    failCall(responseJson.code, responseJson.msg);
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static postJsonWithRaw(urlName, session, data, successCall, failCall)
    {
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请打开手机网络开关');
                }
            }
        });
        var fetchOptions = {
            method: 'POST',
            headers: {
                "Content-Type": "application/json;charset=UTF-8",
                "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                "Tenant-Id": "000000",
                "Blade-Auth": "bearer " + session
            },
            body: data
        };
        console.log('url is ' + urlName + '?' + data);
        LoadingUtils.showLoading();
        fetch(urlName, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                // Spinner.hide();
                LoadingUtils.dismissLoading();
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.code == 200)
                {
                    successCall(responseJson.code, responseJson.data);
                }
                else
                {
                    failCall(responseJson.code, responseJson.msg);
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static postJson(urlName, session, data, successCall, failCall)
    {
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请打开手机网络开关');
                }
            }
        });
        var keySet = Object.keys(data).sort();
        var param = '';
        for (var index in keySet)
        {
            var key = keySet[index];
            var value = data[key];
            if (value != '')
            {
                param = param + key + '=' + value + '&';
            }
        }
        param = param.substr(0, param.length - 1);
        var sign = Crypto.MD5(param + Constant.salt);
        var postData = param + '&sign=' + sign
        var fetchOptions = {
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                "Tenant-Id": "000000",
                "Blade-Auth": "bearer " + session
            },
            body: postData
        };
        console.log('url is ' + urlName + '?' + postData);
        LoadingUtils.showLoading();
        fetch(urlName, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                // Spinner.hide();
                LoadingUtils.dismissLoading();
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.code == 200)
                {
                    successCall(responseJson.code, responseJson.data);
                }
                else
                {
                    failCall(responseJson.code, responseJson.msg);
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static login(urlName, data, successCall, failCall)
    {
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请打开手机网络开关');
                }
            }
        });
        var keySet = Object.keys(data).sort();
        var param = '';
        for (var index in keySet)
        {
            var key = keySet[index];
            var value = data[key];
            if (value != '')
            {
                param = param + key + '=' + value + '&';
            }
        }
        param = param.substr(0, param.length - 1);
        var sign = Crypto.MD5(param + Constant.salt);
        var postData = param + '&sign=' + sign
        var fetchOptions = {
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                "Tenant-Id": "000000",
                "User-Type": 'app'
            },
            body: postData
        };
        console.log('url is ' + urlName + '?' + postData);
        // Spinner.show();
        LoadingUtils.showLoading();
        fetch(urlName, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                // Spinner.hide();
                LoadingUtils.dismissLoading();
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.error == 'invalid_grant')
                {
                    failCall(responseJson.error, responseJson.error);
                }
                else
                {
                    successCall(responseJson, responseJson);
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    // //get请求
    // /**
    //  *url :请求地址
    //  *callback:回调函数
    //  */
    // static getJson(url, successCall)
    // {
    //     fetch(url)
    //         .then((response) => response.json())
    //         .then((responseJson) =>
    //         {
    //             successCall(responseJson);
    //         }).done();
    // }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static postJsonWithoutLoading(urlName, data, successCall, failCall)
    {
        NetInfo.isConnected.fetch().done((isConnected) =>
        {
            // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
            if (!isConnected)
            {
                if (Platform.OS === 'android')
                {
                    ToastUtils.toastShortBottom('该设备无网络连接,请先打开手机网络开关');
                }
            }
        });
        var keySet = Object.keys(data).sort();
        var param = '';
        for (var index in keySet)
        {
            var key = keySet[index];
            var value = data[key];
            if (value != '')
            {
                param = param + key + '=' + value + '&';
            }
        }
        param = param.substr(0, param.length - 1);
        var sign = Crypto.MD5(param + Constant.salt);
        var postData = param + '&sign=' + sign
        var fetchOptions = {
            method: 'POST',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: postData
        };
        console.log('url is ' + urlName + '?' + postData);
        fetch(urlName, fetchOptions)
            .then((response) => response.json())
            .then((responseJson) =>
            {
                console.log('responseJson is ' + JSON.stringify(responseJson));
                if (responseJson.resultcode == '0000')
                {
                    successCall(responseJson.resultcode, responseJson.data);
                }
                else
                {
                    failCall(responseJson.resultcode, '');
                }
            }).catch(e =>
        {
            console.log(`error ${e}`)
        });
    }

    static uploadPic(method, uri, successCall, failCall)
    {
        StorageUtils.get('session').then((session) =>
        {
            let formData = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
            let multipartFile = {uri: uri, type: 'multipart/form-data', name: 'image.png'};
            formData.append("files", multipartFile);   //这里的files就是后台需要的key
            LoadingUtils.showLoading();
            fetch(method, {
                method: 'POST',
                headers: {
                    "Content-Type": "multipart/form-data",
                    "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                    "Tenant-Id": "000000",
                    "Blade-Auth": "bearer " + session
                },
                body: formData,
            })
                .then((response) => response.json())
                .then((responseJson) =>
                {
                    LoadingUtils.dismissLoading();
                    console.log('responseJson is ' + JSON.stringify(responseJson));
                    if (responseJson.code == 200)
                    {
                        successCall(responseJson.code, responseJson.data);
                    }
                    else
                    {
                        failCall(responseJson.code, responseJson.msg);
                    }
                })
                .catch((error) =>
                {
                    console.error('error', error)
                });
        });
    }

    static uploadAudio(method, uri, successCall, failCall)
    {
        StorageUtils.get('session').then((session) =>
        {
            let formData = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
            let multipartFile = {uri: uri, type: 'multipart/form-data', name: 'test.mp3'};
            formData.append("files", multipartFile);   //这里的files就是后台需要的key
            LoadingUtils.showLoading();
            fetch(method, {
                method: 'POST',
                headers: {
                    "Content-Type": "multipart/form-data",
                    "Authorization": "Basic YXBwOmFwcF9zZWNyZXQ=",
                    "Tenant-Id": "000000",
                    "Blade-Auth": "bearer " + session
                },
                body: formData,
            })
                .then((response) => response.json())
                .then((responseJson) =>
                {
                    LoadingUtils.dismissLoading();
                    console.log('responseJson is ' + JSON.stringify(responseJson))
                    console.log('responseJson.code  is ' + JSON.stringify(responseJson.code));
                    if (responseJson.code == 200)
                    {
                        successCall(responseJson.code, responseJson.data);
                    }
                    else
                    {
                        failCall(responseJson.code, responseJson.msg);
                    }
                })
                .catch((error) =>
                {
                    console.error('error', error)
                });
        });
    }
}
